package com.telit.firecommand.listener;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * <p>自定义异步异常捕获</p>
 *
 * @author yuzhanxiang
 * @copyright 天立泰科技股份有限公司
 * @since 2022/5/19 17:29
 **/
@Slf4j
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        String paramsMsg = StrUtil.EMPTY;
        if (ArrayUtil.isNotEmpty(params)) {
            final AtomicInteger serialize = new AtomicInteger(0);
            paramsMsg = Arrays.stream(params).map(p ->
                    StrUtil.format("参数[{}]=[{}]", serialize.getAndAdd(1), JSONUtil.toJsonStr(p))
            ).collect(Collectors.joining(StrUtil.COMMA));
        }

        final String errorMsg = StrUtil.format("异步未捕获的异常:[{}],执行方法:[{}],方法参数：[{}]",
                ObjectUtil.isNotNull(ex) ? ex.getMessage() : "未知堆栈信息",
                ObjectUtil.isNotNull(method) ? method.getName() : "未知方法名",
                paramsMsg
        );
        log.error(errorMsg);
    }
}
